package com.whfc;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description xxl-job配置
 * @Author hw
 * @Date 2021-08-28 16:42
 * @Version 1.0
 */
@Configuration
@ConditionalOnProperty(value = "xxl.job.enable", havingValue = "true")
public class XxlJobConfig {

    private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);

    @NacosValue("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @NacosValue("${xxl.job.executor.appname}")
    private String appname;

    @NacosValue("${xxl.job.executor.logpath}")
    private String logPath;

    @NacosValue("${xxl.job.executor.port}")
    private int port;

    @NacosValue("${xxl.job.executor.logretentiondays}")
    private int logRetentionDays;

    @NacosValue("${xxl.job.accessToken:}")
    private String accessToken;

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
        xxlJobSpringExecutor.setPort(port);
        xxlJobSpringExecutor.setAppname(appname);
        xxlJobSpringExecutor.setLogPath(logPath);
        xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
        
        // 设置访问令牌
        if (accessToken != null && !accessToken.trim().isEmpty()) {
            xxlJobSpringExecutor.setAccessToken(accessToken);
            logger.info(">>>>>>>>>>> xxl-job accessToken configured: {}", accessToken);
        } else {
            logger.warn(">>>>>>>>>>> xxl-job accessToken is empty, this may cause registration failure");
        }
        
        return xxlJobSpringExecutor;
    }
}